import { useEffect } from 'react';
import { useLocation, useParams } from 'umi';
import useDispatcher from './useDispatcher';
import initialValues from '../components/pageSetting/index';
import { isEmpty } from 'lodash';

export default function () {
  const params = useParams<Record<'type', string>>();
  const history = useLocation() as unknown as Location & Record<'query', any>;

  const dispatch = useDispatcher();

  const isEdit = params.type === 'edit';
  const isCreate = params.type === 'create';

  const { query = {} } = history;
  const pageParam = {
    id: query?.id,
    name: decodeURIComponent(query?.name || ''),
    type: query?.type || 1,
    channelCode: query?.channel,
  };

  useEffect(() => {
    // 更新路由参数
    if (!isEmpty(pageParam)) {
      dispatch('updatePageParam', pageParam);
    }
    // 创建--空白模版时进入
    if (isCreate && pageParam.id === '0') {
      dispatch('pageDataToPreview', { ...initialValues.initialValues, components: [] });
    }
    // 创建--非空白模版时进入
    if (isCreate && pageParam.id !== '0') {
      dispatch('getTplData', pageParam.id);
    }
    // 编辑--时进入
    if (isEdit && pageParam.id) {
      dispatch('getPageData', pageParam);
    }
    // 获取所有的虚拟商品
    dispatch('getGoodsData', {});
  }, []);

  return {
    isEdit,
    isCreate,
    pageParam,
  };
}
